<template>
  <div class="forget-password-modal">
    <!-- 修复visible属性绑定 -->
    <el-dialog :model-value="visible" @update:model-value="handleClose" title="找回密码" width="400px"
      :close-on-click-modal="false">
      <!-- 步骤指示器 -->
      <div class="step-indicator">
        <div :class="{ 'step-item': true, 'active': step === 1 }">
          <span class="step-number">1</span>验证身份
        </div>
        <div :class="{ 'step-item': true, 'active': step === 2 }">
          <span class="step-number">2</span>重置密码
        </div>
      </div>

      <!-- 第一步：验证身份 -->
      <div v-if="step === 1" class="form-container">
        <el-form :model="forgetData" :rules="step1Rules" ref="step1FormRef" label-position="top">
          <el-form-item label="注册账号" prop="account">
            <el-input v-model="forgetData.account" placeholder="请输入您的注册账号" prefix-icon="User" clearable />
          </el-form-item>

          <!-- 恢复邮箱输入框 -->
          <el-form-item label="个人邮箱" prop="email">
            <el-input v-model="forgetData.email" placeholder="请输入您的个人邮箱" prefix-icon="Message" clearable />
          </el-form-item>

          <!-- 验证码输入 -->
          <el-form-item label="验证码" prop="code">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-input v-model="forgetData.code" placeholder="请输入验证码" prefix-icon="Lock" clearable />
              </el-col>
              <el-col :span="8">
                <el-button :disabled="countdown > 0 || !forgetData.account || !forgetData.email"
                  @click="sendVerificationCode" type="primary">
                  {{ countdown > 0 ? `${countdown}s后重新发送` : '发送验证码' }}
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleStep1Submit" style="width: 100%">下一步</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 第二步：重置密码 -->
      <div v-if="step === 2" class="form-container">
        <el-form :model="forgetData" :rules="step2Rules" ref="step2FormRef" label-position="top">
          <el-form-item label="新密码" prop="password">
            <el-input v-model="forgetData.password" type="password" placeholder="请输入新密码" prefix-icon="Lock"
              show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="rpassword">
            <el-input v-model="forgetData.rpassword" type="password" placeholder="请再次输入密码" prefix-icon="Lock"
              show-password />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleStep2Submit" style="width: 100%">确认重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, inject } from 'vue';
import { FormInstance, FormRules } from 'element-plus';
import { sendVerificationCodeAPI, verifyCodeAPI, resetPasswordAPI } from '@/api/user';
import { ElMessage } from 'element-plus';


// 表单类型定义
interface ForgetForm {
  account: string;  // 修改为字符串类型以支持多种账号格式
  email: string;
  code: string;
  password: string;
  rpassword: string;
}

// 组件参数 - 修复类型定义错误
const props = defineProps<{
  visible: boolean;
}>(); // 添加缺失的函数调用括号

// 使用字符串数组格式声明事件以增强类型兼容性
const emit = defineEmits(['update:visible', 'resetSuccess']);

// 响应式数据
const forgetData = reactive<ForgetForm>({
  account: '',
  email: '',
  code: '',
  password: '',
  rpassword: ''
});
const step = ref(1); // 当前步骤
const countdown = ref(0); // 验证码倒计时
const step1FormRef = ref<FormInstance>();
const step2FormRef = ref<FormInstance>();


// 第一步验证规则
const step1Rules = reactive<FormRules<ForgetForm>>({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 16, message: '账号长度在4-16个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入您的邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' }
  ]
});

// 第二步验证规则
const step2Rules = reactive<FormRules<ForgetForm>>({
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/, message: '密码需包含大小写字母和数字，长度8-16位', trigger: 'blur' }
  ],
  rpassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== forgetData.password) {
          callback(new Error('两次密码输入不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ]
});

// 发送验证码
const sendVerificationCode = async () => {
  if (!step1FormRef.value) return;
  const valid = await step1FormRef.value.validateField(['account', 'email']);
  if (!valid) return;

  try {
    await sendVerificationCodeAPI({
      account: forgetData.account,
      email: forgetData.email.trim() // 添加.trim()确保无空格
    });
    ElMessage.success('验证码发送成功，如未收到请检查垃圾邮件文件夹');
    // 开始倒计时
    countdown.value = 60;
    const timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) clearInterval(timer);
    }, 1000);
  } catch (error) {
    ElMessage.error('验证码发送失败，请重试');
  }
};

// 第一步提交（验证身份）
const handleStep1Submit = async () => {
  if (!step1FormRef.value) return;
  const valid = await step1FormRef.value.validate();
  if (!valid) return;

  try {
    await verifyCodeAPI({
      account: forgetData.account,
      code: forgetData.code // 移除email参数
    });
    step.value = 2; // 验证通过进入第二步
  } catch (error) {
    ElMessage.error('验证码错误或已过期');
  }
};

// 添加关闭对话框方法
const handleClose = (value: boolean) => {
  emit('update:visible', value);
};

// 第二步提交（重置密码）
const handleStep2Submit = async () => {
  if (!step2FormRef.value) return;
  const valid = await step2FormRef.value.validate();
  if (!valid) return;

  try {
    await resetPasswordAPI({
      account: forgetData.account,
      code: forgetData.code, // 添加验证码参数
      password: forgetData.password
    });
    ElMessage.success('密码重置成功，请使用新密码登录');
    emit('update:visible', false);
    emit('resetSuccess'); // 确保事件正确派发
    // 重置表单
    Object.assign(forgetData, { account: '', email: '', code: '', password: '', rpassword: '' });
    step.value = 1;
  } catch (error) {
    ElMessage.error('密码重置失败，请重试');
  }
};
</script>

<style scoped lang="scss">
.forget-password-modal {
  .step-indicator {
    display: flex;
    margin-bottom: 20px;

    .step-item {
      flex: 1;
      text-align: center;
      padding: 1px 0;
      position: relative;
      font-weight: 500;

      .step-number {
        display: inline-block;
        width: 24px;
        height: 24px;
        line-height: 24px;
        border-radius: 50%;
        background: #e5e7eb;
        color: #606266;
        margin-right: 8px;
      }

      &.active {
        color: #409eff;

        .step-number {
          background: #409eff;
          color: white;
        }
      }
    }
  }

  .form-container {
    padding: 10px;
  }
}
</style>